package com.example.sparkchaindemo.utils;

import android.app.Application;
import android.os.Environment;
import android.util.Log;

import com.example.sparkchaindemo.R;
import com.iflytek.aikit.core.AiHelper;
import com.iflytek.aikit.core.BaseLibrary;
import com.iflytek.aikit.core.CoreListener;
import com.iflytek.aikit.core.ErrType;
import com.iflytek.aikit.core.LogLvl;
import com.iflytek.sparkchain.core.SparkChain;
import com.iflytek.sparkchain.core.SparkChainConfig;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class SparkUtils {
    private static final int MAX_LOG_LENGTH = 4000; // 最大日志长度

    public static void writeFile(String path, byte[] bytes) {
        boolean append = false;
        try {
            File file = new File(path);
            if (file.exists()) {
                append = true;
            } else {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(path, append);//指定写到哪个路径中
            FileChannel fileChannel = out.getChannel();
            fileChannel.write(ByteBuffer.wrap(bytes)); //将字节流写入文件中
            fileChannel.force(true);//强制刷新
            fileChannel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    public static void longLog(String tag, String message) {
        if (message.length() > MAX_LOG_LENGTH) {
            int chunkCount = message.length() / MAX_LOG_LENGTH; // 计算需要分成多少段
            for (int i = 0; i <= chunkCount; i++) {
                int max = MAX_LOG_LENGTH * (i + 1);
                if (max >= message.length()) {
                    Log.d(tag, message.substring(MAX_LOG_LENGTH * i));
                } else {
                    Log.d(tag, message.substring(MAX_LOG_LENGTH * i, max));
                }
            }
        } else {
            Log.d(tag, message);
        }
    }


    public static boolean deleteDirectory(String filePath) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (File file : files) {
            // 删除子文件
            if (file.isFile()) {
                flag = file.delete();
                if (!flag) break;
            }
            // 删除子目录
            else if (file.isDirectory()) {
                flag = deleteDirectory(file.getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        // 删除当前目录
        return dirFile.delete();
    }


    public static void saveToFile(String fileName, String inputText) {
        File file = new File(fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(inputText.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int initSparkChainSDK(Application application) {
        // 初始化SDK，Appid等信息在清单中配置
        SparkChainConfig sparkChainConfig = SparkChainConfig.builder();
        sparkChainConfig.appID(application.getResources().getString(R.string.appid))
                .apiKey(application.getResources().getString(R.string.apikey))
                .apiSecret(application.getResources().getString(R.string.apiSecret))//应用申请的appid三元组
                //   .uid("")
                .logLevel(666);

        String result;
//        if(ret == 0){
//            result = "SDK初始化成功,请选择相应的功能点击体验。";
//            isAuth = true;
//        }else{
//            result = "SDK初始化失败,错误码:" + ret;
//            isAuth = false;
//        }
//        Log.d(TAG,result);
//        showInfo(result);

        return SparkChain.getInst().init(application, sparkChainConfig);
    }

    public static void initAiKitSDK(Application application, CoreListener coreListener) {
        AiHelper.getInst().setLogInfo(LogLvl.VERBOSE, 1, application.getFilesDir().getAbsolutePath() + "/resource");
        //设定初始化参数
        BaseLibrary.Params params = BaseLibrary.Params.builder()
                .appId(application.getResources().getString(R.string.appid))  //您的应用ID，可从控制台查看
                .apiKey(application.getResources().getString(R.string.apikey)) //您的APIKEY，可从控制台查看
                .apiSecret(application.getResources().getString(R.string.apiSecret)) //您的APISECRET，可从控制台查看
                .workDir(application.getFilesDir().getAbsolutePath() + "/resource") //SDK的工作目录，需要确保有读写权限。一般用于存放离线能力资源，日志存放目录等使用。
                .build();
        //初始化SDK
        new Thread(new Runnable() {
            @Override
            public void run() {
                AiHelper.getInst().initEntry(application, params);
            }
        }).start();
        if (coreListener == null) {
            AiHelper.getInst().registerListener(new CoreListener() {
                @Override
                public void onAuthStateChange(final ErrType type, final int code) {
                    switch (type) {
                        case AUTH:
                            if (code == 0) {//SDK授权成功
                            } else {//SDK授权失败，授权码为:code
                            }
                            break;
                        case HTTP://SDK状态：HTTP认证结果code
                            break;
                        default://SDK状态：其他错误code
                    }
                }
            });// 注册SDK 初始化状态监听
        } else {
            AiHelper.getInst().registerListener(coreListener);// 注册SDK 初始化状态监听
        }

        initResource(application);
    }

    private static void initResource(Application application){
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileUtils.copyAssetsIVWToPrivateDir(application,"resource");
            }
        }).start();
    }

}
